package com.fsoft.core.framework;

import java.util.HashSet;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import com.fsoft.core.utils.OgnlUtils;

public class DecryptPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
	private static Logger log = LoggerFactory.getLogger(DecryptPropertyPlaceholderConfigurer.class);
	private static String key = "6c082b8cbb1f6fef";

	public static void main(String[] args) throws Exception {
		System.out.println(OgnlUtils.aesEncode(key, "asdf$1234", "utf-8"));
	}

	@Override
	protected String convertProperty(String propertyName, String propertyValue) {
		if (isEncryptPropertyVal(propertyName)) {
			String ret = null;
			try {
				ret = decncryptString(propertyValue);
			} catch (Exception e) {
				log.error(e.getMessage(), e);
			}
			if (null == ret) {
				log.error("属性[" + propertyName + "]的密文错误!");
			}
			return ret;
		}
		return propertyValue;
	}

	public static String decncryptString(String str) throws Exception {
		if (StringUtils.isNotBlank(str))
			return OgnlUtils.aesDecode(key, str, "UTF-8").trim();
		return str;
	}

	private boolean isEncryptPropertyVal(String propertyName) {
		return keys.contains(propertyName);
	}

	/*** 配置文件中记录的值为密文的key */
	private final static Set<String> keys = new HashSet<String>();
	static {
//		keys.add("jdbc.password");
		keys.add("redis.password");
	}
}
